package com.example.springmvcproject.Configuration;



import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.util.Properties;

/*
@Configuration定义配置类，一般和@Bean注解联合使用，
@Configuration注解主要标注在某个类上，相当于xml配置文件中的<beans>
@Bean注解主要标注在某个方法上，相当于xml配置文件中的<bean> 
*/
@Configuration
public class MyBatisConfig {

    @Bean
    public MapperScannerConfigurer getMapperScannerConfigurer() {
        MapperScannerConfigurer msc = new MapperScannerConfigurer();
        //等同于<property name="basePackage" value="com.itheima.dao"/>
        msc.setBasePackage("com.example.springmvcproject.Mapper");
        return msc;
    }
    @Bean
    public PageInterceptor getPageInterceptor(){
        PageInterceptor pageInterceptor = new PageInterceptor();
        Properties properties = new Properties();
        properties.setProperty("helperDialect", "mysql");
        properties.setProperty("supportMethodsArguments","true");
        properties.setProperty("reasonable","true");
        properties.setProperty("autoRuntimeDialect","true");
        pageInterceptor.setProperties(properties);

        return pageInterceptor;
    }

    @Bean
    public SqlSessionFactory getSqlSessionFactoryBean(@Autowired DataSource dataSource,@Autowired PageInterceptor pageInterceptor) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setTypeAliasesPackage("com.example.springmvcproject.Pojo");
        factoryBean.setPlugins(pageInterceptor);
        //配置Mapper.xml扫描路径
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:Mappers/*.xml"));
        return factoryBean.getObject();
    }
}

